<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="house_id" label="房屋ID" required>
        <uni-data-select collection="houses" field="name as text, _id as value" placeholder="关联的房屋ID" v-model="formData.house_id"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="user_id" label="用户ID">
        <uni-data-select collection="uni-id-users" field="username as text, _id as value" placeholder="关联的用户ID" v-model="formData.user_id"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="tenant_name" label="租户姓名" required>
        <uni-easyinput placeholder="租户姓名" trim="both" v-model="formData.tenant_name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="tenant_phone" label="租户手机号" required>
        <uni-easyinput placeholder="租户联系电话" trim="both" v-model="formData.tenant_phone"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="tenant_id_card" label="租户身份证" required>
        <uni-easyinput placeholder="租户身份证号码" trim="both" v-model="formData.tenant_id_card"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="lease_start" label="租赁开始时间" required>
        <uni-datetime-picker type="date" placeholder="请选择租赁开始日期" return-type="timestamp" v-model="formData.lease_start"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="lease_end" label="租赁结束时间">
        <uni-datetime-picker type="date" placeholder="请选择租赁结束日期" return-type="timestamp" v-model="formData.lease_end"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="rent_amount" label="月租金">
        <uni-easyinput type="number" placeholder="每月租金金额" v-model="formData.rent_amount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="deposit_type" label="押金方式">
        <uni-easyinput placeholder="租赁押金方式" v-model="formData.deposit_type"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="deposit_amount" label="押金金额">
        <uni-easyinput type="number" placeholder="租赁押金金额" v-model="formData.deposit_amount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="租赁状态">
        <uni-data-select :localdata="formOptions.status_localdata" v-model="formData.status"></uni-data-select>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/leases.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'leases';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "house_id": "",
        "user_id": "",
        "tenant_name": "",
        "tenant_phone": "",
        "tenant_id_card": "",
        "lease_start": null,
        "lease_end": null,
        "rent_amount": null,
        "deposit_type": "",
        "deposit_amount": null,
        "status": "生效中"
      }
      return {
        formData,
        formOptions: {
          "status_localdata": [
            {
              "value": "生效中",
              "text": "生效中"
            },
            {
              "value": "已到期",
              "text": "已到期"
            },
            {
              "value": "已终止",
              "text": "已终止"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
